#!/usr/bin/env python

import argparse

from common.docker_helpers import (check_root, create_volumes, start_container,
                                   connect_to_container, stop_container,
                                   restore_file_ownership)


def parse_args():
    parser = argparse.ArgumentParser()
    opts = parser.add_mutually_exclusive_group()
    opts.add_argument('-d', '--debug', help='Use bash to connect',
                      action='store_true')
    parser.add_argument('-t', '--tag', help='Docker image tag to run. Default'
                                            ' is latest, try develop to get'
                                            ' the latest w3af features.',
                        required=False)
    opts.add_argument('-c', '--config-file',
                      help='Path to REST API config file in YAML format.',
                      required=False, dest='api_config_file')
    return parser.parse_args()


if __name__ == '__main__':
    check_root()

    args = parse_args()
    create_volumes()

    docker_run = ('docker run'
                  ' -d'
                  ' -v ~/.w3af:/root/.w3af'
                  ' -v ~/w3af-shared:/root/w3af-shared'
                  ' -p 5000:5000'
                  ' -p 44444:44444'
                  ' andresriancho/w3af')

    container_id = start_container(args.tag, command=docker_run)

    if args.debug:
        cmd = '/bin/bash'
    elif args.api_config_file: 
        cmd = '/home/w3af/w3af/w3af_api 0.0.0.0:5000 -c %s' % args.api_config_file
    else:
        cmd = '/home/w3af/w3af/w3af_api 0.0.0.0:5000'

    try:
        connect_to_container(container_id, cmd)
    finally:
        stop_container(container_id)
        restore_file_ownership()
